<!DOCTYPE html>
<html lang="en">

<head>
  <meta charset="UTF-8">
  <meta http-equiv="X-UA-Compatible" content="IE=edge">
  <meta name="viewport" content="width=device-width, initial-scale=1.0">
  <title>Document</title>
</head>

<body>
  <script>
    // 构造函数food
    function Food(name, price, ingredients) {
      // 名称
      this.name = name;
      // 价格
      this.price = price;
      // 原料数组
      this.ingredients = ingredients || [];
    }
    // 向 ingredients 数组中添加一种原料
    Food.prototype.addIngredient = function (name, weight) {
      this.ingredients.push({ name, weight });
    };
    // removeIngredient 方法从 ingredients 数组中删除一种原料
    Food.prototype.removeIngredient = function (name) {
      const index = this.ingredients.findIndex(ingredient => ingredient.name === name);
      if (index !== -1) {
        this.ingredients.splice(index, 1);
      }
    };
    // calculateTotalWeight 方法计算食品总重量
    Food.prototype.calculateTotalWeight = function () {
      return this.ingredients.reduce((totalWeight, ingredient) => totalWeight + ingredient.weight, 0);
    };
    // toString 方法返回食品的字符串表示
    Food.prototype.toString = function () {
      const ingredientsString = this.ingredients.map(ingredient => `${ingredient.name}(${ingredient.weight}g)`).join("、");
      return `名称：${this.name}，价格：${this.price}，原料：${ingredientsString}`;
    }
    const food1 = new Food("牛肉干", 25);
    food1.addIngredient("牛肉", 100);
    food1.addIngredient("盐", 5);
    console.log(food1.toString()); // 名称：牛肉干，价格：25，原料：牛肉(100g)、盐(5g)
    console.log(food1.calculateTotalWeight()); // 105
    const food2 = new Food("薯片", 8, [{ name: "土豆", weight: 50 }, { name: "食用油", weight: 20 }, { name: "盐", weight: 2 }]);
    food2.removeIngredient("食用油");
    console.log(food2.toString()); // 名称：薯片，价格：8，原料：土豆(50g)、盐(2g)
    console.log(food2.calculateTotalWeight()); // 52
  </script>
</body>

</html>